package com.hrt.freemaker;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.htmlparser.util.ParserException;

import com.btcode.web.core.unit.WebContext;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMakerUtil {
    /**
     * 导出Word
     *
     * @param root
     * @param templateFile
     * @param downloadfilename
     * @throws IOException
     */
    protected void outWord(Map<String, Object> root, String templateFile, String downloadfilename) throws IOException {
        HttpServletRequest resq = WebContext.getRequest();
        HttpServletResponse res = WebContext.getResponse();
        @SuppressWarnings("deprecation")
        Configuration config = new Configuration();
        String tempPath = resq.getServletContext().getRealPath("/") + "/webResource/freeMarkerTemp/";
        config.setDirectoryForTemplateLoading(new File(tempPath));
        config.setDefaultEncoding("UTF-8");
        Template t = config.getTemplate(templateFile, "UTF-8");
        Writer out = res.getWriter();
        try {
            res.setContentType("application/x-msdownload;charset=utf-8");
            res.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(downloadfilename, "utf-8"));
            t.process(root, out);
        }
        catch (TemplateException e) {
            e.printStackTrace();
        }
        out.flush();
    }

    /**
     * 导出excel，结合freemarker模板，先转成html然后通过poi输出成excel
     * @param tempName 模板名称
     * @param data 数据
     * @param downloadfilename 下载的文件名
     * @throws IOException
     * @throws ParserException
     */
    public void exportExcelWidthFreemarkerTemp(String tempName, String baseExcelField, HashMap<String, Object> data, String downloadfilename) throws IOException, ParserException {
        HttpServletRequest resq = WebContext.getRequest();
        HttpServletResponse res = WebContext.getResponse();
        String tempPath = resq.getServletContext().getRealPath("/") + "/webResource/freeMarkerTemp/";
        tempPath = tempPath.replaceAll("\\\\", "/");

        OutputStream out = res.getOutputStream();
        downloadfilename = toUtf8String(WebContext.getRequest(), downloadfilename);
        res.setContentType("application/x-msdownload;charset=utf-8");
        res.setHeader("Content-Disposition",
                "attachment;filename=" + new String(downloadfilename.getBytes("utf-8"), "ISO-8859-1"));
        ExcelCreater excelCreater = new ExcelCreater();
        excelCreater.exportExcel(tempPath,baseExcelField, tempName, data, out);
        out.flush();
        out.close();

    }

    public static String toUtf8String(HttpServletRequest request, String downloadfilename) {
        String agent = request.getHeader("User-Agent");
        try {
            boolean isFireFox = (agent != null && agent.toLowerCase().indexOf("firefox") != -1);
            if (isFireFox) {
                downloadfilename = new String(downloadfilename.getBytes("UTF-8"), "ISO8859-1");
            }
            else {
                downloadfilename = toUtf8String(downloadfilename);
                if ((agent != null && agent.indexOf("MSIE") != -1)) {
                    final int i150 = 150;
                    if (downloadfilename.length() > i150) {
                        // 根据request的locale 得出可能的编码
                        downloadfilename = new String(downloadfilename.getBytes("UTF-8"), "ISO8859-1");
                    }
                }
            }
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return downloadfilename;
    }

    public static String toUtf8String(String downloadfilename) {

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < downloadfilename.length(); i++) {
            char c =downloadfilename.charAt(i);
            final int i255 = 255;
            final int i256 = 256;
            if (c >= 0 && c <= i255) {
                sb.append(c);
            }
            else {
                byte[] b;
                try {
                    b = Character.toString(c).getBytes("utf-8");
                }
                catch (Exception ex) {
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) {
                        k += i256;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }
}
